# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:zzly
@file:serializers.py
@time:2020/09/08
"""
from rest_framework import serializers

from apps.member.models import MemberRecord
from apps.project_case.models import House, Room


class HouseAppSeializer(serializers.ModelSerializer):
    style = serializers.CharField(source='style.name')
    thumbnail = serializers.SerializerMethodField(read_only=True)
    is_collect = serializers.SerializerMethodField()

    def get_is_collect(self, obj):
        user = self.context['request'].user
        if user.is_anonymous:
            return False
        return MemberRecord.is_collect(obj, user.member)

    def get_thumbnail(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    class Meta:
        model = House
        fields = ('id', 'is_collect', 'address', 'describe', 'area', 'collect_count', 'style', 'thumbnail')


class HouseDetailAppSeializer(serializers.ModelSerializer):
    rooms = serializers.SerializerMethodField()
    style = serializers.CharField(source='style.name')
    thumbnail = serializers.SerializerMethodField(read_only=True)
    is_collect = serializers.SerializerMethodField()

    def get_is_collect(self, obj):
        user = self.context['request'].user
        if user.is_anonymous:
            return False
        return MemberRecord.is_collect(obj, user.member)

    def get_thumbnail(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    def get_rooms(self, obj):
        rooms = Room.objects.filter(house=obj, delete=False).order_by('-id')
        return RoomDetailAppSerializer(rooms, many=True).data

    class Meta:
        model = House
        fields = (
        'id', 'is_collect', 'thumbnail', 'address', 'describe', 'area', 'collect_count', 'style', 'thumbnail', 'rooms')


class RoomDetailAppSerializer(serializers.ModelSerializer):
    thumbnail = serializers.SerializerMethodField(read_only=True)

    def get_thumbnail(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    class Meta:
        model = Room
        fields = ('id', 'thumbnail', 'name', 'describe')
